package com.cskaoyan.gateway.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IUserService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.*;
import com.mall.user.intercepter.TokenIntercepter;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@CrossOrigin(value = "*", allowCredentials = "true")
@RestController
@RequestMapping("user")
public class UserController {

    @Reference(timeout = 50000,retries = 0,check = false)
    private IUserService userService;

    @Anoymous
    @PostMapping("register")
    public ResponseData register(@RequestBody IUserRegisterRequest request){
        //封装request参数
        //远程过程调用
        IUserRegisterResponse response = userService.register(request);

        if(response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil<>().setData("success");
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    @Anoymous
    @PostMapping("login")
    public ResponseData login(@RequestBody IUserLoginRequest request, HttpServletResponse servletResponse){
        //封装request参数
        //远程过程调用
        IUserLoginResponse response = userService.login(request);

        if(response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            Cookie cookie = CookieUtil.genCookie(TokenIntercepter.ACCESS_TOKEN, response.getToken(), "/", 60 * 60 * 24);
            cookie.setHttpOnly(true);
            servletResponse.addCookie(cookie);
            return new ResponseUtil<>().setData(response);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }


    @PostMapping("info")
    public ResponseData getUserInfo(@RequestBody IUserInfoRequest request, HttpServletRequest servletRequest){

        //1、从TokenInterceptor设置的request域中取出当前登录的userId
        String userInfo = (String) servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        //Json字符串转换为Json对象
        JSONObject object = JSON.parseObject(userInfo);
        long userId = Long.parseLong(object.get("uid").toString());

        //2、封装request
        request.setUserId(userId);

        //3、远程过程调用
        IUserInfoResponse response = userService.getUserInfo(request);

        //4、返回值处理
        if(response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil<>().setData(response);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }
}
